package com.bw.controller;

import cn.hutool.core.util.RandomUtil;
import com.bw.common.ZzyUtils;
import com.bw.entity.User;
import com.bw.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Controller
public class PhoneLoginController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StudentMapper studentMapper;

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/loginPage.do")
    public String loginPage(){

        return "login";
    }

    /**
     * 发送短信
     * ajax 请求必须要加 @ResponseBody注解
     * @param phone
     * @return
     */
    @RequestMapping("/sendCode.do")
    @ResponseBody
    public String sendCode(String phone){

        // 生成一个验证码
        String numbers = RandomUtil.randomNumbers(6);
        // 发送一个短信
        ZzyUtils.sendSms(phone,numbers,5);
        //Redis存储验证码 结构为： 手机号-验证码
        redisTemplate.opsForValue().set(phone,numbers,5, TimeUnit.MINUTES);

        return "发送成功";
    }

    /**
     * 执行登录
     * @param loginUser
     * @param result
     * @param model
     * @return
     */
    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model){

        if (result.hasErrors()){

            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            return "login";
        }
         //判断手机号是否存在
        User userFromDB =  studentMapper.selectUserByPhone(loginUser.getPhone());
        if (userFromDB == null){
            model.addAttribute("error","手机号不存在");

            return "login";
        }

        // 判断手机号验证码是否正确
        String phoneCode = loginUser.getPhoneCode();
        //从Redis中查询验证码（根据用户的手机号查询）
        Object redisPhoneCode = redisTemplate.opsForValue().get(loginUser.getPhone());

        if (!phoneCode.equals(redisPhoneCode)){

            model.addAttribute("error","验证码错误");

            return "login";
        }

        //
        return "success";
    }
}
